package com.toune.movie.mvp.activity;

import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVUser;
import com.tencent.smtt.sdk.TbsVideo;
import com.toune.movie.R;
import com.toune.movie.base.AppConstant;
import com.toune.movie.base.BaseActivity;
import com.toune.movie.base.myUtil.GetTimeUtils;
import com.toune.movie.base.myUtil.GsonBinder;
import com.toune.movie.base.myUtil.MyUtil;
import com.toune.movie.base.myUtil.ProgressWebview;
import com.toune.movie.base.myUtil.ThreadPoolManager;
import com.toune.movie.mvp.contract.WebContract;
import com.toune.movie.mvp.presenter.WebPresenter;
import com.toune.movie.vo.VarietyDetailVo;
import com.vondear.rxtool.RxDataTool;
import com.vondear.rxtool.RxDeviceTool;
import com.vondear.rxtool.view.RxToast;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2018/5/17.
 */

public class WebActivity extends BaseActivity<WebPresenter> implements WebContract.View {
    @BindView(R.id.progress_wv)
    ProgressWebview progressWv;
    @BindView(R.id.last_ll)
    LinearLayout lastLl;
    @BindView(R.id.next_ll)
    LinearLayout nextLl;
    @BindView(R.id.media_control_ll)
    LinearLayout mediaControlLl;
    //    @BindView(R.id.webview)
//    WebView webview;
    private String url;
    private List<VarietyDetailVo.SourceList.DataBean> dataBeans;
    private int position;
    private int tag;
    private List<VarietyDetailVo.SourceList> sourList;
    private String src;
    private boolean isDetail = true;

    @Override // 实例化presenter
    public WebPresenter initPresenter() {
        return new WebPresenter();
    }

    @Override
    public void loadMore() {

    }

    @Override
    public void refreData() {

    }

    @Override
    public void init(Bundle savedInstanceState) {
        url = getIntent().getStringExtra("url");
        String datasStr = getIntent().getStringExtra("datas");
        tag = getIntent().getIntExtra("tag", 0);
        if (tag == 2) {
            sourList = GsonBinder.toList(datasStr, VarietyDetailVo.SourceList.class);
        } else if (tag > 0) {
            dataBeans = GsonBinder.toList(datasStr, VarietyDetailVo.SourceList.DataBean.class);
        }
        position = getIntent().getIntExtra("positon", 0);
        startVideo();
        MyUtil.showADDialog(context);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // 绑定toobar跟menu
        getMenuInflater().inflate(R.menu.menu, menu);
        return true;
    }

    private void startVideo() {
        String title = "VIP视频";
        if (tag == 2) {
            if (sourList != null && sourList.size() > 0) {
                title = sourList.get(position).getTitle();
                mediaControlLl.setVisibility(View.VISIBLE);
            } else {
                mediaControlLl.setVisibility(View.GONE);
            }
        } else if (tag > 0) {
            if (dataBeans != null && dataBeans.size() > 0) {
                title = dataBeans.get(position).getName();
                mediaControlLl.setVisibility(View.VISIBLE);
            } else {
                mediaControlLl.setVisibility(View.GONE);
            }
        }

        AVObject history = new AVObject(AppConstant.TABLE_HIS);
        history.put("title", title);
        history.put("url", url);
        history.put("time", GetTimeUtils.dateFormat());
        history.put("tag", 1); //区别VIP视频还是网站视频
        if (AVUser.getCurrentUser() != null) {
            history.put("userId", AVUser.getCurrentUser().getObjectId());
        }
        history.put("phoneId", RxDeviceTool.getUniqueSerialNumber());
        history.saveInBackground();
        getWindow().getDecorView().addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @RequiresApi(api = Build.VERSION_CODES.ICE_CREAM_SANDWICH)
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                ArrayList<View> outView = new ArrayList<View>();
                getWindow().getDecorView().findViewsWithText(outView, "QQ浏览器", View.FIND_VIEWS_WITH_TEXT);
                int size = outView.size();

                if (outView != null && outView.size() > 0) {
                    outView.get(0).setVisibility(View.GONE);
                }
            }
        });
        getHtmlUrl();
    }


    private void getHtmlUrl() {
        ThreadPoolManager.getInstatnce().createShortThreadPool().execute(new Runnable() {
            @Override
            public void run() {
                try {
                    Document doc = Jsoup.connect(url).get();
                    Elements iframe = doc.getElementsByTag("iframe");
                    url = iframe.attr("src");
                    while (isDetail) { //目的是将广告全部剔除
                        doc = Jsoup.connect(url).get();
                        iframe = doc.getElementsByTag("iframe");
                        if (iframe == null || iframe.size() == 0) {
                            src = url;
                            isDetail = false;
                        } else {
                            url = iframe.attr("src");
                        }
                    }
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            progressWv.loadUrl(src);
//                            TbsVideo.openVideo(context,src);
                        }
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_web;
    }

    @Override
    protected String getTitleStr() {
        titleStr = getIntent().getStringExtra("title");
        if (RxDataTool.isEmpty(titleStr)) {
            titleStr = "视频播放";
        }
        return titleStr;
    }

    @Override
    protected void initEventAndData() {
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
//                switch (item.getItemId()) {
//                    case R.id.chrome_menu:
                MyUtil.intentToLocalChrom(context, url);
//                        break;
//                }
                return true;
            }
        });
    }

    @Override
    public void showError(String msg) {

    }

    @Override
    public void useNightMode(boolean isNight) {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.last_ll, R.id.next_ll})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.last_ll:
                if (position > 0) {
                    position--;
                    if (tag == 2) {
                        url = AppConstant.JieXi + sourList.get(position).getUrl();
                        toolbar.setTitle(sourList.get(position).getTitle());
                    } else if (tag > 0) {
                        url = AppConstant.JieXi + dataBeans.get(position).getUrl();
                        toolbar.setTitle(dataBeans.get(position).getName());
                    }
                    startVideo();
                } else {
                    RxToast.info("已经是第一集");
                }
                break;
            case R.id.next_ll:
                if (tag == 2) {
                    if (position < sourList.size() - 1) {
                        position++;
                        url = AppConstant.JieXi + sourList.get(position).getUrl();
                        toolbar.setTitle(sourList.get(position).getTitle());
                        startVideo();
                    } else {
                        RxToast.info("已经是最后一集");
                    }
                } else if (tag > 0) {
                    if (position < dataBeans.size() - 1) {
                        position++;
                        url = AppConstant.JieXi + dataBeans.get(position).getUrl();
                        setTitleStr(dataBeans.get(position).getName());
                        startVideo();
                    } else {
                        RxToast.info("已经是最后一集");
                    }
                }
                break;
        }
    }

}
